"use strict";

/**
 * @auther wtfssd
 * Created by wtfssd on 2017/11/16
 */
import * as React from 'react'

const {View, SectionList, TouchableOpacity, DeviceEventEmitter} = require('react-native');
const {connect} = require('react-redux');
const NavigationBar = require('react-native-navbar').default;
const {Actions} = require("react-native-router-flux");
const Sound = require('react-native-sound');
import {commonProps, commonStyles} from "../../assets/styles/common";
import MyTabBar from "../../component/MyTabBar";
import ProductItem from "../../component/ProductItem";
import MyText from "../../component/MyText";
import Colors from "../../assets/styles/Colors";
import Line from "../../component/Line";
import {ViewStyle} from "react-native";
import LoadingView from "../../component/Loading";
import {get_order_info, OrderComponent, orderItem} from "../../interface/index";

class OrderManagerPage extends React.Component<OrderComponent, any> {
    subscription: any;

    constructor(props: any, context: any,) {
        super(props, context);
        this.state = {
            loading: false,
        }
    }

    componentDidMount(): void {
        Sound.setCategory('Playback');
        this.subscription = DeviceEventEmitter.addListener('receiveNewOrder', () => {
            this.props.dispatch({type: 'order/fetchData'});

            this.playSound();
        });
    }

    componentWillUnmount() {
        this.subscription.remove();
    };

    handlePress = (props) => {
        Actions.orderDetail({orderItem: props.section});
    };

    _onChangeTab = ({index}) => {


        console.log('定单管理更改 tab', index);
        this.props.dispatch({
            type: 'order/changeCurrentTab',
            payload: {currentTab: index}
        });
    };


    playSound = () => {
        const whoosh = new Sound('notice.mp3', Sound.MAIN_BUNDLE, (error) => {
            if (error) {
                console.log('failed to load the sound', error);
                return;
            }
            whoosh.play((success) => {
                if (success) {
                    whoosh.pause();
                    whoosh.release();
                } else {
                    whoosh.pause();
                    whoosh.release();
                }
            });
        });
    };

    acceptOrder = (item: orderItem) => {
        this.props.dispatch({
            type: 'order/acceptOrder',
            payload: {order_id: item.id}
        })
    };

    rejectOrder = (item: orderItem) => {
        this.props.dispatch({
            type: 'order/rejectOrder',
            payload: {order_id: item.id}
        })
    };


    onRefresh = () => {
        this.props.dispatch({type: 'order/fetchData'})
    };

    getDataSource = () => {
        switch (this.props.order.currentTab) {
            case 0 :
                return this.props.order.newOrderList.map((item: orderItem, index: number) => ({
                    ...item,
                    data: item.get_order_info
                }));
            case 1 :

                return this.props.order.cancelOrderList.map((item: orderItem, index: number) => ({
                    ...item,
                    data: item.get_order_info
                }));

            case 2 :
                return this.props.order.finishOrderList.map((item: orderItem, index: number) => ({
                    ...item,
                    data: item.get_order_info
                }));


            case 4 :

                return this.props.order.refundOrderList.map((item: orderItem, index: number) => ({
                    ...item,
                    data: item.get_order_info
                }));
            case 3 :

                return this.props.order.progressOrderList.map((item: orderItem, index: number) => ({
                    ...item,
                    data: item.get_order_info
                }));
        }
    };

    getButton = (text: string, style?: ViewStyle | ViewStyle[], onPress?: Function) => {
        return (
            <TouchableOpacity onPress={onPress}>
                <View style={[{
                    paddingHorizontal: 20,
                    paddingVertical: 5,
                    borderWidth: 1,
                    borderColor: '#999999',
                    borderRadius: 10
                }, style]}>
                    <MyText>{text}</MyText>
                </View>
            </TouchableOpacity>
        )

    };

    renderSectionHeader = (props: { section: orderItem }) => {
        const orderItem = props.section;
        return (
            <TouchableOpacity onPress={this.handlePress.bind(this, props)}>
                <View style={{backgroundColor: Colors.White, padding: 10}}>
                    <MyText>{`订单号:${orderItem.order_number}`}</MyText>
                </View>
                {/*<View style={[commonStyles.flexRow, {*/}
                {/*backgroundColor: Colors.BgColor,*/}
                {/*padding: 10,*/}
                {/*alignItems: 'center'*/}
                {/*}]}>*/}
                {/*<MyIcon name={'icon-shop'} color={Colors.Primary}/>*/}
                {/*<MyText style={{marginLeft: 10}}>{this.props.auth.profile.store_name}</MyText>*/}
                {/*</View>*/}
                {/*<Line/>*/}
            </TouchableOpacity>
        )
    };


    renderOptionButtons = (orderItem: orderItem) => {

        switch (this.props.order.currentTab) {
            case 0:
                return (
                    <View style={[commonStyles.flexRow, {
                        backgroundColor: Colors.White,
                        justifyContent: 'flex-end',
                        padding: 10
                    }]}>
                        {this.getButton('接受', {marginRight: 20}, this.acceptOrder.bind(this, orderItem))}
                        {/*{this.getButton('拒绝', null, this.rejectOrder.bind(this, orderItem))}*/}
                    </View>
                );
            default:
                return null;
        }


    };

    renderSectionSeparatorComponent = (item) => {
        const {leadingItem} = item;
        const orderItem: orderItem = item.section;
        const data: get_order_info = item.leadingItem;
        if (!leadingItem || typeof leadingItem === 'undefined') return null;
        const getCount = () => {
            let count = 0;
            if (data) {
                count = data.count
            }
            return Number(count)
        };

        return (
            <View onPress={this.handlePress.bind(this, item)}>
                <View style={[commonStyles.flexRow, {
                    backgroundColor: Colors.White,
                    justifyContent: 'flex-end',
                    padding: 10
                }]}>
                    <MyText>{`共${getCount()}件商品 合计：¥${Number(orderItem.store_price).toFixed(2)}`}</MyText>
                </View>
                <Line/>

                {this.props.order.currentTab === 1 ? null : this.renderOptionButtons(orderItem)}
                <Line height={10} color={Colors.Clear}/>
            </View>
        )
    };


    renderItem = (item) => {
        return (
            <TouchableOpacity onPress={this.handlePress.bind(this, item)}>
                <ProductItem {...item.item}/>
            </TouchableOpacity>
        )
    };


    render() {
        return (
            <View style={commonStyles.container}>
                <NavigationBar {...commonProps.navBar}
                               title={{title: this.props.title, tintColor: '#fff'}}
                />
                <MyTabBar tabs={['新订单', '取消订单', '已完成', '进行中']} onChange={this._onChangeTab.bind(this)}
                          currentTab={this.props.order.currentTab}/>

                <LoadingView style={commonStyles.flex1} loading={this.state.loading}>
                    <SectionList
                        stickySectionHeadersEnabled={false}
                        renderItem={this.renderItem}
                        refreshing={this.props.order.loading}
                        onRefresh={this.onRefresh}
                        ItemSeparatorComponent={() => <Line height={5} color={Colors.White}/>}
                        renderSectionHeader={this.renderSectionHeader}
                        SectionSeparatorComponent={this.renderSectionSeparatorComponent}
                        keyExtractor={(item, index) => index}
                        extraData={this.state}
                        sections={this.getDataSource()}
                    />
                </LoadingView>
            </View>
        );
    }
}


export default connect(
    ({auth, order}) => ({auth, order})
)(OrderManagerPage);